package me.seu.demo.handler;

import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.common.param.QueryParam;
import me.seu.demo.common.param.Term;
import me.seu.demo.common.param.TermType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * ES 通用处理
 *
 * @author liangfeihu
 * @since 2023/8/2 13:10
 */
@Slf4j
@Component
public class ElasticsearchCommonHandler {


    /**
     * 构造es请求体
     */
    public SearchRequest buildSearchRequest(String index, String deviceId,
            QueryParam queryParam) {
        //根据条件构造参数查询
        //布尔查询构造器
        BoolQuery.Builder queryBuilders = QueryBuilders.bool();
        //精确匹配查询构造器
        TermQuery.Builder termBuilder = QueryBuilders.term();
        TermQuery termQuery = termBuilder.field("deviceId").value(deviceId).build();
        //布尔查询增加and条件
        queryBuilders.must(termQuery._toQuery());

        List<Term> termList = QueryParam.getTermsFromJson(queryParam.getTerms());
        for (Term term : termList) {
            String column = term.getColumn();
            if (StringUtils.isBlank(column)) {
                continue;
            }
            if (TermType.eq.equals(term.getTermType())) {
                TermQuery.Builder termBuilderNew = QueryBuilders.term();
                TermQuery termQueryNew = termBuilderNew.field(term.getColumn())
                        .value(term.getValue()).build();
                queryBuilders.must(termQueryNew._toQuery());
            }
        }

        //构建出布尔查询
        BoolQuery boolQuery = queryBuilders.build();
        SearchRequest searchRequest = new SearchRequest.Builder()
                .query(boolQuery._toQuery())
                .sort(o -> o.field(f -> f.field("id").order(SortOrder.Desc)))
                .from(queryParam.getPageIndex() * queryParam.getPageSize())
                .size(queryParam.getPageSize())
                .index(index)
                .build();
        return searchRequest;
    }

}
